package javapop.framework.parser;

import java.util.Set;

import javapop.framework.ParseContext;
import javapop.framework.ParseError;
import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.Parser;

public class Reserved<T> extends Parser<T> {
	private Parser<T> child;
	private Set<T> reserved;
	
	public Reserved(Parser<T> child, Set<T> reserved) {
		if(child==null) {
			throw new IllegalArgumentException("Child parser is <null>");
		}
		if(reserved==null || reserved.isEmpty()) {
			throw new IllegalArgumentException("No reserved value");
		}
		this.child = child;
		this.reserved = reserved;
	}
	
	public boolean isReserved(T value) {
		return reserved.contains(value);
	}
	
	@Override
	public boolean isMemoized() {
		return false;
	}
	
	@Override
	public String getDescription() {
		return child.getDescription();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public ParseResult<T> eval(ParseContext ctx, ParseInput input) {
		ParseResult<T> result = child.parse(ctx,input);
		if(result.isError()) {
			return result;
		}
		
		if(isReserved(result.getResult())) {
			return (ParseResult<T>) new ParseError(""+result.getResult()+" is reserved");
		}
		
		return result;
	}

}
